import React from 'react';
import { Form, Input, Select, message, AutoComplete, Button } from 'antd';
import * as routerActions from 'react-router-redux';
import { getArrayValue } from 'Utils/index';
import { connect } from 'react-redux';
import Api from 'Utils/api';
import { debounce } from 'throttle-debounce';
import EqualBorder from './../../../CommonComponents/EqualBorder';
import './index.scss';

const Option = Select.Option;
const FormItem = Form.Item;
const { TextArea } = Input;
class DispatchPage extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      business: [],
      organise: [],
      peopleInfo: []
    };
    this.renderLawExecutor = ::this.renderLawExecutor;
    this.initOrganise = ::this.initOrganise;
    this.initBusiness = debounce(1000, ::this.initBusiness);
  }
  componentWillMount() {
    this.initOrganise();
  }

  onEnter() {
    const { businessObj, selectBusinessName } = this.state;
    const formValue = this.props.form.getFieldsValue();
    if (!selectBusinessName) {
      this.props.form.setFields({ enterprise_name: { value: formValue.enterprise_name, errors: [new Error('请在下拉框中选择企业')] } });
      return;
    }
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const businessRes = businessObj.filter(item => item.name === formValue.enterprise_name);
        if (businessRes.length === 0) {
          this.props.form.setFields({ enterprise_name: { value: formValue.enterprise_name, errors: [new Error('请在下拉框中选择企业')] } });
          return;
        }
        const api = new Api({
          method: 'POST',
          path: '/tasks',
          data: {
            task_name: formValue.task_name,
            content: formValue.content,
            enterprise_id: businessRes.length > 0 ? businessRes[0].id : '',
            law_organization: formValue.law_organization,
            law_executor_ids: formValue.law_executor,
            law_executor: getArrayValue(this.state.peopleInfo, formValue.law_executor),
          },
          success: (json) => {
            this.props.dispatch(routerActions.push(`/system/dispatch/dispatch/task/${json.id}`));
          },
          err: (msg) => {
            message.error(msg);
          }
        });
        api.run();
      }
    });
  }
  renderLawExecutor() {
    const children = [];
    const { peopleInfo } = this.state;
    for (let i = 0; i < peopleInfo.length; i++) {
      children.push(<Option key={peopleInfo[i].id} >{peopleInfo[i].name}</Option>);
    }
    return children;
  }
  initOrganise() {
    const api = new Api({
      method: 'GET',
      path: '/justices/justice',
      success: (res) => {
        this.setState({
          organise: res
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  handleOrganiseSelect(key) {
    const api = new Api({
      method: 'GET',
      path: `/justices/staff/${key}`,
      success: (res) => {
        this.setState({
          peopleInfo: res
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  // for business
  handleSelect(value) {
    console.log('value', value);
    this.setState({
      selectBusinessName: value,
    });
  }
  handleBusinessChange(value) {
    this.setState({
      inputValue: value.trim()
    }, () => {
      if (this.state.inputValue) {
        this.initBusiness();
      }
    });
  }
  initBusiness() {
    const api = new Api({
      method: 'GET',
      path: '/enterprises',
      query: {
        name_like: this.state.inputValue,
        offset: 0,
        limit: 20
      },
      success: (res) => {
        const datas = res.data_list && res.data_list.length > 0 ? res.data_list : [];
        const business = datas.length > 0 ? res.data_list.map(item => item.name) : [];
        this.setState({
          business: [...business],
          businessObj: res.data_list
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  render() {
    const { form, initialValue } = this.props;
    const { getFieldDecorator } = form;
    const { business, organise, peopleInfo } = this.state;
    return (
      <EqualBorder
        title="发布安检任务"
        content={
          <div className="profession-container">
            <div className="profession-body" style={{ textAlign: 'center', width: '100%' }}>
              <Form layout={'horizontal'} className="report-form" >
                <FormItem label="任务名称" >
                  {getFieldDecorator('task_name', {
                    initialValue: initialValue ? initialValue.task_name : '',
                    rules: [
                      { required: true, message: '请输入任务名称' }
                    ]
                  })(
                    <Input placeholder="请输入任务名称" style={{ width: 840 }} />
                  )}
                </FormItem >
                <FormItem label="任务内容" >
                  {getFieldDecorator('content', {
                    initialValue: initialValue ? initialValue.content : '',
                    rules: [
                      { required: true, message: '请输入任务内容' }
                    ]
                  })(
                    <TextArea placeholder="请输入任务内容" rows={4} style={{ width: 840, height: 150 }} />
                  )}
                </FormItem >
                <FormItem label="企业名称" >
                  {getFieldDecorator('enterprise_name', {
                    initialValue: initialValue ? initialValue.enterprise_name : undefined,
                    rules: [
                      { required: true, message: '请选择企业名称' }
                    ]
                  })(
                    <AutoComplete
                      dataSource={business}
                      placeholder="请选择企业名称"
                      defaultActiveFirstOption={false}
                      onSelect={this.handleSelect.bind(this)}
                      onChange={this.handleBusinessChange.bind(this)}
                    />
                  )}
                </FormItem >
                <FormItem label="执法机构" >
                  {getFieldDecorator('law_organization', {
                    initialValue: initialValue ? initialValue.law_organization : undefined,
                    rules: [
                      { required: true, message: '请选择执法机构' }
                    ]
                  })(
                    <Select placeholder="请选择执法结构" className="sel-input" onSelect={this.handleOrganiseSelect.bind(this)} >
                      {
                        organise && organise.length > 0 ? organise.map((item) => {
                          return (<Option key={item.id} >{item.name}</Option >);
                        }) : ''
                      }
                    </Select >
                  )}
                </FormItem >
                <FormItem label="执法人员" >
                  {getFieldDecorator('law_executor', {
                    initialValue: initialValue ? initialValue.law_executor : [],
                    rules: [
                      { required: true, message: '请选择执法人员' }
                    ]
                  })(
                    <Select placeholder="请选择执法人员" className="sel-input" mode="multiple">
                      {
                        peopleInfo.length > 0 ? this.renderLawExecutor() : ''
                      }
                    </Select >
                  )}
                </FormItem >
              </Form >
            </div >
            <div className="btn-wrap" >
              <Button className="ok-btn" onClick={this.onEnter.bind(this)}>
                <img src="images/dispatch/icon_public.png" alt="" />
                发布
              </Button>
            </div >
          </div>
        }
      />
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing
  };
}

export default Form.create()(connect(mapStateToProps)(DispatchPage));

